<?php
if($_SESSION['login'] != true) {
	die('Access danied');
}
//------------------------------
if(IsSet($_POST['statements'])) {
	$statements = $_POST['statements'];
}
if(IsSet($_POST['insertType'])) {
	$insertType = $_POST['insertType'];
}
//------------------------------

if(!$statements || $statements == '') {
	/* wyswietl formularz */
	?>
	<small><i>Każde hasło w nowej lini.</i></small>
	<form action="<?php echo $PHP_SELF; ?>" method="POST">
		<textarea name="statements" rows="20" cols="80"></textarea>
		<br /><br />
		<div style="width: 550px; text-align: left;">
			Hasła istniejące:<br />
			<input type="radio" name="insertType" checked="checked" value="1" />zbierz ponownie<br />
			<input type="radio" name="insertType" value="2" />pomiń<br />
		</div>	
		<input type="submit" value="Dodaj frazy do bazy danych" />
	</form>
	<?php
} else {
	/* dodawaj do bazy */
	$array = explode("\n", $statements);
	foreach($array as $statement) {
		$statement = trim($statement);
		$statementId = getStatementId($statement);
		if($statementId > 0 && $insertType == 1) {
			//wstaw do ponownego zebrania
			insertNewStatement($statementId, 0);
			?>
			<div style="display: inline; color: blue;">[PONOWNIE]</div> <?php echo $statement; ?><br />
			<?php
		} else if(!$statementId > 0 && $insertType == 2) {
			//wstaw nowe
			insertNewStatement(0, $statement);
			?>
			<div style="display: inline; color: green;">[DODANO]</div> <?php echo $statement; ?><br />
			<?php
		} else {
			?>
			<div style="display: inline; color: red;">[POMINIĘTO]</div> <?php echo $statement; ?><br />
			<?php
		}
	}
}

/*
 *	FUNKCJE
 */

function getStatementId($statement) {
	global $db;
	global $configDbPrefix;
	$sql = "SELECT new_statement_id FROM \"" . $configDbPrefix . "new_statements\" n JOIN \"" . $configDbPrefix . "statements\" s ON (n.statement_id = s.statement_id) WHERE n.statement='$statement' OR s.statement='$statement';";
	#echo $sql . "\n";
	$db->query($sql);
	$rows = $db->fetchArray();
	$rowsNum = count($rows);
	if(!$rowsNum) {
		$sql = "SELECT statement_id FROM \"" . $configDbPrefix . "statements\" WHERE statement='$statement';";
		#echo $sql;
		$db->query($sql);
		$rows = $db->fetchArray();
		$rowsNum = count($rows);
		if($rowsNum) {
			return $rows[0]['statement_id'];
		}
	} else {
		return -1;
	}
}

function insertNewStatement($statementId, $statement) {
	global $db;
	global $configDbPrefix;
	$sql = "INSERT INTO \"" . $configDbPrefix . "new_statements\" ";
	if($statementId && !$statement) {
		$sql .= "(statement_id, insert_timestamp) VALUES ($statementId, 'NOW()')";
	} else if(!$statementId && $statement) {
		$sql .= "(statement, insert_timestamp) VALUES ('$statement', 'NOW()')";
	}
	#echo $sql;
	$db->query($sql);
}

?>
